﻿#include "salewidget.h"
#include "ui_salewidget.h"
#include <QFileDialog>
#include <QMessageBox>
#include "mymessagebox.h"
#include <QPrinter>
#include "readonlydelegate.h"

SaleWidget::SaleWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SaleWidget)
{
    ui->setupUi(this);

    blackPalette.setColor(QPalette::WindowText, Qt::black);
    redPalette.setColor(QPalette::WindowText, Qt::red);

    relation = nullptr;
    totalCount = 0;
    totalMoney = 0.0;

    QAction *actionInsert = new QAction("插入", this);
    QAction *actionDelete = new QAction("删除", this);

    connect(actionDelete, &QAction::triggered,
            [=]()
    {
        int row = ui->tableView->currentIndex().row();
        model->removeRowData(row);
        curRow = model->rowCount()-1;
    });

    connect(actionInsert, &QAction::triggered,
            [=]()
    {
        curRow = ui->tableView->currentIndex().row();
        productPicker.showAndInit();
    });

    menu.addAction(actionInsert);
    menu.addAction(actionDelete);

    model = new SaleModel();
    setSelectionRow();
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->tableView->setModel(model);
    ui->tableView->setSortingEnabled(true);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setListPushButtonAndMenuLabel(ui->pushButtonList, model->header);
    ui->dateEdit->setMinimumDate(Tools::getBaseDate());
    ui->dateEdit->setMaximumDate(QDate::currentDate());
    ui->dateEdit->setDate(QDate::currentDate());
    ui->dateEdit->setDisplayFormat("yyyy-MM-dd");

    connect(ui->tableView, &QTableView::customContextMenuRequested, this, &SaleWidget::showMenu);

    for(int i=0;i<model->columnCount();i++){
        if(i!=4 && i!=5){
            ui->tableView->setItemDelegateForColumn(i, new ReadOnlyDelegate());
        }
    }

    btnImport = ui->pushButtonImport;
    btnPrint = ui->pushButtonPrint;
    btnExport = ui->pushButtonExport;
    btnPreview = ui->pushButtonPreview;

    connect(model, &SaleModel::updateTotal,
            [=](int totalCount, double totalMoney)
    {
        this->totalCount = totalCount;
        this->totalMoney = totalMoney;
        refreshTotalState();
    });

    connect(model, &SaleModel::importDataDone,
            [=]()
    {
        qDebug()<<"导入数据成功";
        MyMessageBox::information("提示","导入数据成功");
    });

    connect(model, &SaleModel::exportDataDone,
            [=]()
    {
        MyMessageBox::information("提示","导出数据成功");
    });

    connect(ui->lineEditNickName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        userPicker.loadData();
        userPicker.exec();
    });

    connect(ui->lineEditContact, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        userPicker.loadData();
        userPicker.exec();
    });

    connect(ui->lineEditTel, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        userPicker.loadData();
        userPicker.exec();
    });

    connect(&userPicker, &UserPicker::selectedFinished,
            [=](UserRelation *relation)
    {
        this->relation = relation;
        dingdan.targetUsername = relation->targetUsername;
        dingdan.targetCompanyId = relation->targetCompanyId;
        ui->lineEditNickName->setText(relation->nickName);
        ui->lineEditContact->setText(relation->contact);
        ui->lineEditTel->setText(relation->tel);
        ui->comboBox->setCurrentIndex(relation->hasTicketHistory);
        if(widgetType == Dingdan::SaleOut || widgetType == Dingdan::SaleBack){
            ui->labelTicket->setText("应开发票："+QString::number(relation->ticketOut-relation->preTicketOut, 'f', 2));
            ui->labelMoney->setText("应收货款："+QString::number(relation->moneyIn-relation->preMoneyIn, 'f', 2));
        }else{
            ui->labelTicket->setText("应收发票："+QString::number(relation->ticketIn-relation->preTicketIn, 'f', 2));
            ui->labelMoney->setText("应付货款："+QString::number(relation->moneyOut-relation->preMoneyOut, 'f', 2));
        }
    });

    connect(ui->tableView, &QTableView::doubleClicked,
            [=](const QModelIndex index)
    {
        if(index.row() == model->rowCount()-1){
            productPicker.showAndInit();
        }
    });

    connect(&saleCalculateWidget, &SaleCalculateWidget::calculateDingdanSuccess,
            [=]()
    {
        this->clear();
    });

    connect(&productPicker, &ProductPicker::selectedFinished,
            [=](QList<Product*> products, int defaultCount)
    {
        if(defaultCount < 0)defaultCount=0;
        model->insertProduct(curRow, products, defaultCount);
        curRow = model->rowCount()-1;
    });

    connect(&dingdanPicker, &DingdanPicker::selectedFinished,
            [=](Dingdan *dingdan)
    {
        this->initWithDingdan(*dingdan);
    });

    connect(&dingdanImportWidget, &DingdanImportWidget::importDingdanSuccess,
            [=](Dingdan *dingdan)
    {
        this->initWithDingdan(*dingdan);
    });

    connect(&dingdanService, &DingdanService::getDingdanDetailSuccess,
            [=]()
    {
        model->insertDingdanDetail(this->dingdan.details);
    });

    connect(&dingdanService, &DingdanService::saveDingdanSuccess,
            [=]()
    {
        this->clear();
    });

    connect(&dingdanService, &DingdanService::deleteDingdanSuccess,
            [=]()
    {
        this->clear();
    });

    connect(&productService, &ProductService::getAllHistoryProdyctsSuccess,
            [=](QList<HistoryProduct*> historyProducts)
    {
        model->updateProductPrice(historyProducts);
    });
}

SaleWidget::~SaleWidget()
{
    delete ui;
}

void SaleWidget::showMenu(const QPoint point){
    if(model->currentDingdanDetails().size() != 0){
        QModelIndex index = ui->tableView->indexAt(point);
        if(index.isValid() && index.row() != model->rowCount()-1){
            menu.exec(QCursor::pos());
        }
    }
}

void SaleWidget::showMessage(QString message)
{
    QMessageBox::information(this, "提示", message);
}

void SaleWidget::setWidgetType(Dingdan::DingdanType widgetType)
{
    this->widgetType = widgetType;
    dingdan.state = Dingdan::SAVED;
    dingdan.type = widgetType;
    dingdanPicker.setDingdansState(Dingdan::SAVED);
    dingdanPicker.setDingdanType(widgetType);
    dingdanImportWidget.setWidgetType(widgetType);
    saleCalculateWidget.setWidgetType(widgetType);
    switch (widgetType) {
    case Dingdan::SaleOut:
        userPicker.setIsShowPlatformUser(true);
        userPicker.setWidgetType(UserRelation::Client);
        model->setWidgetType(UserRelation::Client);
        ui->tableView->initHiddenStateList("sale_out", model->header.size());
        ui->labelTypeName->setText("销售单");
        ui->labelTypeName->setPalette(blackPalette);
        ui->labelName->setText("客户名称");
        ui->pushButtonImport->setVisible(true);
        dingdanImportWidget.setDingdansState(Dingdan::WAITFORSALEOUT);
        ui->labelTicket->setText("应开发票：0.0");
        ui->labelMoney->setText("应收货款：0.0");
        ui->pushButtonSetting->setSettingKey("saleout");
        break;
    case Dingdan::SaleBack:
        userPicker.setIsShowPlatformUser(false);
        userPicker.setWidgetType(UserRelation::Client);
        model->setWidgetType(UserRelation::Client);
        ui->tableView->initHiddenStateList("sale_back", model->header.size());
        ui->labelTypeName->setText("销退单");
        ui->labelTypeName->setPalette(redPalette);
        ui->labelName->setText("客户名称");
        ui->pushButtonImport->setVisible(true);
        dingdanImportWidget.setDingdansState(Dingdan::WAITFORSALEBACK);
        ui->labelTicket->setText("应开发票：0.0");
        ui->labelMoney->setText("应收货款：0.0");
        ui->pushButtonSetting->setSettingKey("saleback");
        break;
    case Dingdan::PurchaseIn:
        userPicker.setIsShowPlatformUser(false);
        userPicker.setWidgetType(UserRelation::Giver);
        model->setWidgetType(UserRelation::Giver);
        ui->tableView->initHiddenStateList("purchase_in", model->header.size());
        ui->labelTypeName->setText("采购单");
        ui->labelTypeName->setPalette(blackPalette);
        ui->labelName->setText("供应商名称");
        ui->pushButtonImport->setVisible(true);
        dingdanImportWidget.setDingdansState(Dingdan::WAITFORPURCHASEIN);
        ui->labelTicket->setText("应收发票：0.0");
        ui->labelMoney->setText("应付货款：0.0");
        ui->pushButtonSetting->setSettingKey("purchasein");
        break;
    case Dingdan::PurchaseBack:
        userPicker.setIsShowPlatformUser(true);
        userPicker.setWidgetType(UserRelation::Giver);
        model->setWidgetType(UserRelation::Giver);
        ui->tableView->initHiddenStateList("purchase_back", model->header.size());
        ui->labelTypeName->setText("采退单");
        ui->labelTypeName->setPalette(redPalette);
        ui->labelName->setText("供应商名称");
        ui->pushButtonImport->setVisible(false);
        ui->labelTicket->setText("应收发票：0.0");
        ui->labelMoney->setText("应付货款：0.0");
        ui->pushButtonSetting->setSettingKey("purchaseback");
        break;
    case Dingdan::PurchaseDingdan:
        break;
    default:
        break;
    }
}

void SaleWidget::setSelectionRow(){
    model->appendRow(*(new QList<QStandardItem*>));
    ui->tableView->setSpan(model->rowCount()-1, 0, 1, model->columnCount());
    curRow = model->rowCount()-1;
}

void SaleWidget::clear(){
    model->reset();
    setSelectionRow();
    ui->tableView->refreshHiddenState();

    ui->lineEditNickName->setEnabled(true);
    ui->lineEditContact->setEnabled(true);
    ui->lineEditTel->setEnabled(true);
    ui->comboBox->setEnabled(true);
    ui->lineEditNickName->clear();
    ui->lineEditContact->clear();
    ui->lineEditTel->clear();
    ui->lineEditDingdanId->clear();
    ui->lineEditDingdanRemark->clear();
    ui->dateEdit->setDate(QDate::currentDate());
    this->relation = nullptr;
    dingdan.clear();
}

void SaleWidget::refreshTotalState(){
    ui->labelTotalCount->setText(QString("总数量：%1").arg(totalCount));
    ui->labelTotalMoney->setText("总金额："+QString::number(totalMoney, 'f', 2));
}

void SaleWidget::initWithDingdan(Dingdan &dingdan){
    clear();
    this->dingdan.copy(dingdan);
    ui->lineEditDingdanId->setText(dingdan.dingdanId);
    ui->lineEditDingdanRemark->setText(dingdan.remark);
    ui->comboBox->setCurrentIndex(dingdan.isTicket);
    ui->dateEdit->setDate(QDate::fromString(dingdan.date, "yyyy-MM-dd"));
    UserRelation *relation = dingdan.getUserRelation();
    if(relation != nullptr){
        this->relation = relation;
        ui->lineEditNickName->setText(relation->nickName);
        ui->lineEditContact->setText(relation->contact);
        ui->lineEditTel->setText(relation->tel);
    }

    ui->lineEditNickName->setEnabled(dingdan.relatedDingdanId.isEmpty());
    ui->lineEditContact->setEnabled(dingdan.relatedDingdanId.isEmpty());
    ui->lineEditTel->setEnabled(dingdan.relatedDingdanId.isEmpty());

    if(this->dingdan.details.size()==0){
        dingdanService.getDingdanDetails(this, &this->dingdan);
    }else{
        model->insertDingdanDetail(dingdan.details);
    }
}

void SaleWidget::on_pushButtonImport_clicked()
{
    dingdanImportWidget.showAndInit();
}

void SaleWidget::on_pushButtonExport_clicked()
{
    QString path = QFileDialog::getSaveFileName(
                this,
                "Save",
                "../",
                "source(*.xls *.xlsx)");

    if(!path.isEmpty())
    {
        model->exportDataToExcel(path);
    }
}

void SaleWidget::on_pushButtonNew_clicked()
{
    if(model->rowCount() > 1 || !dingdan.targetUsername.isEmpty()){
        int res = QMessageBox::question(this, "提示", "是否保存订单？", tr("保存"), tr("取消"));
        switch (res) {
        case 0:
            SaleWidget::on_pushButtonSave_clicked();
            break;
        case 1:
            break;
        }
    }else{
        clear();
        QMessageBox::information(this, "信息", "新建成功！");
    }
}

void SaleWidget::on_pushButtonPrint_clicked()
{
    printManager.setPrintSetting(ui->pushButtonSetting->getPrintSetting());
    printManager.preparePrint(model);
    printManager.print();
}

void SaleWidget::on_pushButtonPreview_clicked()
{
    printManager.setPrintSetting(ui->pushButtonSetting->getPrintSetting());
    printManager.preparePrint(model);
    printManager.preview();
}

void SaleWidget::on_pushButtonOpen_clicked()
{
    dingdanPicker.showAndInit();
}

void SaleWidget::on_comboBox_currentIndexChanged(int index)
{
    Q_UNUSED(index);
    refreshTotalState();
}

void SaleWidget::on_pushButtonSave_clicked()
{
    dingdan.isTicket = ui->comboBox->currentIndex();
    dingdan.date = ui->dateEdit->text();
    dingdan.remark = ui->lineEditDingdanRemark->text();
    dingdan.details = model->currentDingdanDetails();
    dingdanService.saveDingdan(this, dingdan);
}

void SaleWidget::on_pushButtonDelete_clicked()
{
    int res;
    if(dingdan.dingdanId.isEmpty()){
        res = QMessageBox::question(this, "提示", "是否作废单据？", tr("是"), tr("否"));
        if(res == 0){
           clear();
        }
    }else{
        res = QMessageBox::question(this, "提示", "当前订单已保存，是否仍然删除？", tr("是"), tr("否"));
        if(res == 0){
            dingdanService.deleteDingdan(this, dingdan);
        }
    }
}

void SaleWidget::on_pushButtonSubmit_clicked()
{
    dingdan.isTicket = ui->comboBox->currentIndex();
    dingdan.date = ui->dateEdit->text();
    dingdan.remark = ui->lineEditDingdanRemark->text();
    dingdan.details = model->currentDingdanDetails();
    if(dingdan.targetUsername.isEmpty()){
        if(dingdan.type == Dingdan::SaleOut || dingdan.type == Dingdan::SaleBack){
            QMessageBox::warning(this, "警告", "未选择客户！");
        }else{
            QMessageBox::warning(this, "警告", "未选择供应商！");
        }
        return;
    }

    if(dingdan.details.size() == 0){
        QMessageBox::warning(this, "警告", "未选择商品！");
        return;
    }

    saleCalculateWidget.setTicketState(ui->comboBox->currentIndex()==0);
    saleCalculateWidget.showWithDingdan(&dingdan);
}

void SaleWidget::on_pushButtonPrice_clicked()
{
    productService.getAllHistoryProdycts(
                this,
                this->relation,
                model->currentDingdanDetails());
}
